require "Net/send_Msg"
require "Net/TitleHandler"
require 'View/UIBase/UIBase'

UIPetTryPart = UIBase.New(PanelNames.UIPetTryPart);
local titleDecGroup = {};
local titleCount = 0;
local titleDecCount = 0;
function UIPetTryPart.Init(func)
    UIBase.Init(UIPetTryPart, func);
end

--定义控件
function UIPetTryPart:OnCreate()
    titleDecGroup = {};
    self.titlesData = {};
    self.showTitles = {};
    for k, v in pairs(G.dataTable["t_medal"]) do
        if titleDecGroup[v.f_GroupId] == nil then
            titleDecGroup[v.f_GroupId] = {};
        end
        table.insert(titleDecGroup[v.f_GroupId], v);
        table.sort(titleDecGroup[v.f_GroupId], function(a, b)
            return a.f_LevelId > b.f_LevelId
        end)
        table.insert(self.titlesData, v);
    end

    self.maxPage = math.ceil(#titleDecGroup / 12);

    table.sort(self.titlesData, function(a, b)
        return a.f_Id < b.f_Id
    end)

    local badgeList = self:GetChild("badgeList");
    self.titleDecList = badgeList:GetChild("list");
    self.titleDecBackBtn = badgeList:GetChild("back");
    self.bg = self:GetChild("btnBack");
    self.dragBounds = self:GetChild("dragBounds");
    self.backBtn = self:GetChild("btnBack");
    self.lastBtn = self:GetChild("last");
    self.nextBtn = self:GetChild("next");
    self.nowPageText = self:GetChild("NowPage");
    self.badgeListController = self:GetController("BadgeList");
    self.pageController = self:GetController("page");
    self.pageController.selectedIndex = 0;
    self.maxPageText = self:GetChild("TotalPage");
    self.maxPageText.text = self.maxPage;
    local pageBtnController = self:GetController("pageBtn");
    pageBtnController.selectedIndex = self.maxPage > 1 and 1 or 0;
    self:refreshChangeBtn();

    self.badges = {}
    self.badgeRect = {}
    self.badgePos = {}
    self.badgeIdx = {};
    self.titleList = self:GetChild("list");

    self:addEvent();
    self:RegisterEvent(Config.EventType.TitleInfo, self.setInfo);
    logicMgr.TitleManager.setIsNewTitle(0);
    --self.CloseFom();
end

function UIPetTryPart:OnEnable()

end

function UIPetTryPart:OnDisable()

end

function UIPetTryPart:OnDestroy()
    self:UnRegisterEvent(Config.EventType.TitleInfo, self.setInfo, self);

end

function UIPetTryPart:addEvent()
    --btnChangeFormation.onClick:Add(function()
    --    self.ShowSelectFom(1);
    --end);
    self:RegisterOnClick(self.backBtn, self.onCloseClick);
    self:RegisterOnClick(self.bg, self.onCloseClick);


end

function UIPetTryPart:removeEvent()
    ----bt_SetBtn.onClick:Clear();
    --self.backBtn.onClick:Clear();
    --self.bg.onClick:Clear();
    --self.lastBtn.onClick:Clear();
    --self.nextBtn.onClick:Clear();
    --self.titleDecBackBtn.onClick:Clear();
end

function UIPetTryPart:onCloseClick()
    self:saveTitle();
    closeUI(PanelNames.UIPetTryPart);
end

function UIPetTryPart:rendererShowTitle()

end

function UIPetTryPart:setInfo()

    self.titleList.itemRenderer = self.rendererTitles;
    titleCount = 0;
    self.titleList.numItems = #titleDecGroup;
end



function UIPetTryPart:rendererTitles(item)
    titleCount = titleCount + 1;
    local idx = titleCount;
    local showId = 0
    local data = nil;
    for i = 1, #titleDecGroup[idx] do
        local titleInfo = UIPetTryPart:getTitleInfoById(titleDecGroup[idx][i].f_Id);
        if UIPetTryPart:getTitleInfoById(titleDecGroup[idx][i].f_Id) ~= nil and ((titleInfo.lastTime - HelperFunc.GetServerTime()) > 0 or titleInfo.lastTime == -1) then
            data = titleDecGroup[idx][i];
            break ;
        end
    end
    local name = item:GetChild("name");
    local ranklevel = item:GetChild("ranklevel");
    local icon = item:GetChild("icon");
    local decBtn = item:GetChild("btnDec");
    local lockController = item:GetController("mask");
    local chooseController = item:GetController("choose");
    chooseController.selectedIndex = 0;
    if data == nil then
        data = titleDecGroup[idx][#titleDecGroup[idx]]
        lockController.selectedIndex = 1;

    else
        lockController.selectedIndex = 0;
        item.onTouchEnd:Clear();
        item.onTouchEnd:Add(function()
            UIPetTryPart:OnTouchUp(data, item);
        end)
        --item.onClick:Clear();
        --item.onClick:Add(function()
        --    UIPetTryPart:clickTitle(data.f_Id, item);
        --end);
        for i = 1, #UIPetTryPart.showTitles do
            if UIPetTryPart.showTitles[i].id == data.f_Id then
                chooseController.selectedIndex = 1;
                break ;
            end
        end
    end
    UIPetTryPart.itemTitleForId[data.f_Id] = item;
    --decBtn.onClick:Clear();
    --decBtn.onClick:Add(function()
    --    UIPetTryPart:showTitleDec(data.f_GroupId);
    --end)

    item.onTouchBegin:Clear();
    item.onTouchMove:Clear();
    item.onTouchBegin:Add(function(evt)
        UIPetTryPart:OnTouchStart(evt, data);
    end)
    item.onTouchMove:Add(function(evt)
        UIPetTryPart:OnTouchMove(evt);
    end)


    icon:GetController("state").selectedIndex = 1;
    icon.icon = "ui://ICONAtlas/" .. data.f_MedalPic;
    name.text = getLanguage(data.f_MedalName);
    ranklevel.text = data.f_LevelId;

end

function UIPetTryPart:OnTouchStart(evt, heroData)
    self.lastEventX = evt.inputEvent.x;
    self.lastEventY = evt.inputEvent.y;
    self.isTouching = true;
    self.timerId = utimer.timeCall(function()

        if self.timerId ~= nil then
            if math.abs(self.lastEventY - evt.inputEvent.y) > 5 or math.abs(self.lastEventX - evt.inputEvent.x) > 5 then
                --utimer.remove(self.timerId);
                self.timerId = nil;
                self.isTouching = false;
                return;
            end
        end

        self.isNotNeedEnable = true;
        UIPetTryPart:showTitleDec(heroData.f_GroupId);
        self.timerId = nil;
    end, 500, 1);
end

--function UIPetTryPart:OnTouchMove(evt)
--    if self.timerId ~= nil then
--        if math.abs(self.lastEventY - evt.inputEvent.y) > 5 or math.abs(self.lastEventX - evt.inputEvent.x) > 5 then
--            utimer.remove(self.timerId);
--            self.timerId = nil;
--            self.isTouching = false;
--        end
--    end
--end

function UIPetTryPart:OnTouchUp(data, item)
    if self.timerId ~= nil and self.isTouching then
        utimer.remove(self.timerId);
        --上阵
        UIPetTryPart:clickTitle(data.f_Id, item);
        self.timerId = nil;
    end
end

function UIPetTryPart:clickTitle(id, obj)
    local beDelete = false;
    local beInsert = false;
    local beInsertNum = 0;
    for i = 1, #self.showTitles do
        if self.showTitles[i].id == id and id ~= 0 then
            if obj == nil then
                obj = self.itemTitleForId[id];
            end
            obj:GetController("choose").selectedIndex = 0;
            self.showTitles[i].id = 0;
            self.showTitles[i].info = {};
            beDelete = true;
            break ;
        end

    end
    if not beDelete then
        for i = 1, #self.showTitles do
            if self.showTitles[i].id == 0 then
                beInsertNum = i;
                beInsert = true;
                break ;
            end
        end
    else
        self:rendererShowTitle();
        return ;
    end

    if beInsert then
        if beInsertNum > 0 then
            self.showTitles[beInsertNum].id = id;
            self.showTitles[beInsertNum].info = G.dataTable["t_medal"][tostring(id)]
            if obj ~= nil then
                obj:GetController("choose").selectedIndex = 1;
            end
            self:rendererShowTitle();
        end

    else
        --展示勋章满了
    end
end

function UIPetTryPart:showTitleDec(groupId)
    self.badgeListController.selectedIndex = 1;
    curTitleDecs = titleDecGroup[groupId];
    self.titleDecList.itemRenderer = self.rendererTitlesDec;
    titleDecCount = 0;
    self.titleDecList.numItems = #curTitleDecs;

end

function UIPetTryPart:rendererTitlesDec(item)
    titleDecCount = titleDecCount + 1;
    local idx = titleDecCount;

    local info = curTitleDecs[idx]
    local lockController = item:GetController("lock");
    item:GetController("arrow").selectedIndex = idx - 1 == 0 and 1 or 0;
    local infoDecText = item:GetChild("info");
    local name = item:GetChild("name");
    local ranklevel = item:GetChild("ranklevel");
    local data = UIPetTryPart:getTitleInfoById(info.f_Id);
    local icon = item:GetChild("icon");
    icon:GetController("state").selectedIndex = 1;
    icon.icon = "ui://ICONAtlas/" .. info.f_MedalPic;
    if data == nil or ((data.lastTime - HelperFunc.GetServerTime()) <= 0 and data.lastTime ~= -1) then
        lockController.selectedIndex = 1;
        local locktips = item:GetChild("locktips");
        locktips.text = getLanguage(info.f_MedalUnlockDes);
    else
        local timeController = item:GetController("timelimit");
        local arrowController = item:GetController("arrow");
        arrowController.selectedIndex = idx - 1 == 0 and 1 or 0;
        local dateText = item:GetChild("date");
        local date = formatUnixTime2Date(data.bornTime);

        lockController.selectedIndex = 0;

        dateText.text = date.year .. "-" .. date.month .. "-" .. date.day;

        if data.lastTime <= -1 then
            timeController.selectedIndex = 0;
        else
            item:GetChild("timelimit").text = timeToTimeLeft(data.lastTime - HelperFunc.GetServerTime(), nil, true);
            timeController.selectedIndex = 1;
        end
    end
    infoDecText.text = getLanguage(info.f_MedalDes);
    name.text = getLanguage(info.f_MedalName);
    ranklevel.text = info.f_LevelId;

end

function UIPetTryPart:saveTitle()
    saveList = {}
    saveList.showList = {};
    for i = 1, #self.showTitles do
        local idNum = 0;
        if self.showTitles[i].id == 0 then
            table.insert(saveList.showList, nil);

        else
            table.insert(saveList.showList, self.showTitles[i].id);
        end
    end
    TitleHandler:SaveShowTitle(saveList.showList);

end

return UIPetTryPart;